<template>
  <div class="tracetask-container">
    <v-layout wrap justify-start align-center>
      <v-flex md12 d-flex>
        <v-flex md2 px-2>
          <v-text-field v-model="queryForm.orderNumber" :label="$t('task.taskId')"></v-text-field>
        </v-flex>
        <v-flex md2 px-2>
          <!-- <v-text-field v-model="queryForm.siteId" :label="$t('task.site')"></v-text-field> -->
          <v-select :items="sites" :label="$t('task.site')" v-model="queryForm.siteId"></v-select>
        </v-flex>
        <v-flex md2 px-2>
          <v-select
            v-model="queryForm.orderStatus"
            :items="orderStatus"
            :label="$t('task.taskStatus')"
          ></v-select>
        </v-flex>

        <v-flex md2 px-2>
          <v-btn round class="subTitle" color="primary" @click="onQuery">
            <span>{{ $t('task.query')}}</span>
            <v-icon>search</v-icon>
          </v-btn>
        </v-flex>
      </v-flex>

      <v-flex md6 d-flex justify-start align-center>
        <v-flex md3>
          <v-btn round class="subTitle" color="secondary" @click="onBatchConfirmOrder">
            <span>{{ $t('order.batch') + $t('order.confirm')+ $t('order.order')}}</span>
            <v-icon>done_all</v-icon>
          </v-btn>
        </v-flex>
        <v-flex md3>
          <v-btn round class="subTitle" dark color="teal lighten-2" @click="onBatchConfirmReview">
            <span>{{ $t('order.batch') + $t('order.confirm')+ $t('order.review')}}</span>
            <v-icon>done_all</v-icon>
          </v-btn>
        </v-flex>
      </v-flex>

      <!-- table -->
      <v-flex md12 class="elevation-1">
        <v-data-table
          v-model="selected"
          :headers="headers"
          :items="tableData"
          select-all
          hide-actions
          item-key="orderNumber"
        >
          <template v-slot:headers="props">
            <tr>
              <th>
                <v-checkbox
                  :input-value="props.all"
                  :indeterminate="props.indeterminate"
                  color="primary"
                  hide-details
                  @click.stop="toggleAll"
                ></v-checkbox>
              </th>
              <th
                v-for="header in props.headers"
                :key="header.text"
                :class="['column sortable', pagination.descending ? 'desc' : 'asc', header.value === pagination.sortBy ? 'active' : '']"
                @click="changeSort(header.value)"
              >
                <!-- <v-icon small>arrow_upward</v-icon> -->
                {{ header.text }}
              </th>
            </tr>
          </template>
          <template v-slot:items="props">
            <tr :active="props.selected" @click="props.selected = !props.selected">
              <td>
                <v-checkbox :input-value="props.selected" color="primary" hide-details></v-checkbox>
              </td>
              <td class="text-xs-center">{{ props.item.orderNumber }}</td>
              <td class="text-xs-center">{{ props.item.siteName }}</td>
              <td class="text-xs-center">{{ props.item.productAsin }}</td>
              <td class="text-xs-center">{{ props.item.price }}</td>
              <td class="text-xs-center">{{ props.item.totalPrice }}</td>
              <td class="text-xs-center">{{ props.item.taskType | TaskType }}</td>
              <td class="text-xs-center">{{ props.item.orderStatus | OrderStatus}}</td>
              <td class="text-xs-center">{{ getTime(props.item.createTime) }}</td>
              <td width="20%" class="text-xs-center mini-button">
                <v-layout wrap>
                  <v-flex md12 d-flex>
                    <!-- <v-btn
                      round
                      small
                      outline
                      class="subTitle"
                      color="accent"
                      @click.stop="onPay(props.item)"
                      v-if="props.item.orderStatus === 6"
                    >
                      <div class="mr-1">{{ $t('base.pay')}}</div>
                    </v-btn> -->
                    <v-btn
                      round
                      small
                      outline
                      class="subTitle"
                      color="red"
                      @click.stop="onObsolete(props.item)"
                      v-if="props.item.orderStatus === 1"
                    >
                      <div class="mr-1">{{ $t('base.invalid')}}</div>
                    </v-btn>
                    <v-btn
                      round
                      small
                      outline
                      class="subTitle"
                      color="secondary"
                      @click.stop="onDetail(props.item)"
                    >
                      <div class="mr-1">{{ $t('base.detail')}}</div>
                    </v-btn>
                  </v-flex>
                  <v-flex md12 d-flex justify-space-around>
                    <v-btn
                      round
                      small
                      outline
                      class="subTitle"
                      color="indigo"
                      @click.stop="onConfirmOrder(props.item)"
                      v-if="props.item.orderStatus === 3 && props.item.taskType !== 1"
                    >
                      <div class="mr-1">{{ $t('base.confirm2') + $t('order.order')}}</div>
                    </v-btn>
                    <v-btn
                      round
                      small
                      outline
                      class="subTitle"
                      color="teal lighten-1"
                      @click.stop="onAccomplishOrder(props.item)"
                      v-if="(props.item.orderStatus === 3 && props.item.taskType === 1) || (props.item.orderStatus === 5 && props.item.taskType !== 1) "
                    >
                      <div class="mr-1">完成订单</div>
                    </v-btn>
                  </v-flex>
                </v-layout>
              </td>
            </tr>
          </template>

          <template v-slot:no-data>
            <v-alert :value="true" outline color="warning" icon="info">{{ $t('base.nodata') }}</v-alert>
          </template>

          <template v-slot:footer>
            <td :colspan="headers.length">
              <v-layout>
                <v-flex md1>合计</v-flex>
                <v-flex md3>{{ getTotal }}</v-flex>
              </v-layout>
            </td>
          </template>
        </v-data-table>

        <v-layout class="pagination-wrapper">
          <v-flex md10 d-flex justify-start align-center>
            <v-flex d-flex md2 justify-start align-center>
              <v-flex md4 class="title-color">{{ $t('base.display') }}</v-flex>
              <v-flex md4>
                <v-select
                  @change="onPageOptionChange"
                  :items="pageOptions"
                  v-model="pagination.limit"
                ></v-select>
              </v-flex>
              <v-flex md4 class="title-color">{{ $t('base.limit') }}</v-flex>
            </v-flex>
            <v-flex
              md2
              class="title-color"
            >{{ $t('base.allTog') }} {{ pagination.pageCount }} {{ $t('base.itemData') }}</v-flex>
            <v-flex md2></v-flex>
            <v-flex md4>
              <v-pagination
                @input="onPageChange"
                :length="pagination.pageCount"
                circle
                total-visible="5"
                v-model="pagination.page"
              ></v-pagination>
            </v-flex>
            <v-flex md2></v-flex>
          </v-flex>
        </v-layout>
      </v-flex>
    </v-layout>

    <v-dialog v-model="dialog" max-width="800">
      <v-card>
        <v-card-title class="title">{{ dialogTitle }}</v-card-title>
        <v-card-text class="title">
          <v-layout align-center justify-center>
            <!-- <v-flex md12 v-if="dialogType === 1">
              <div>订单截图</div>
              <div class="mt-2">
                <img class="dialog-image" :src="dialogData.orderImg ? dialogData.orderImgArr[1] : '' " alt />
              </div>
            </v-flex>
            <v-flex md12 v-if="dialogType === 2">
              <div>评价截图</div>
              <div class="mt-2">
                <img class="dialog-image" :src="!dialogData.orderImgArr ? '' : dialogData.orderImgArr[0]" alt />
              </div>
            </v-flex> -->
            <v-flex md12 v-if="dialogType === 1 || dialogType === 2|| dialogType === 3">
              <v-layout align-center justify-center>
                <v-flex md6>
                  <!-- <div>订单截图</div> -->
                  <div class="mt-2">
                    <img class="dialog-image" :src="dialogData.orderImg ?  dialogData.orderImgArr[0] : ''" alt />
                  </div>
                </v-flex>
                <v-flex md6>
                  <!-- <div>评价截图</div> -->
                  <div class="mt-2">
                    <img class="dialog-image" :src="!dialogData.orderImgArr ? '' : dialogData.orderImgArr[1]" alt />
                  </div>
                </v-flex>
              </v-layout>
            </v-flex>
          </v-layout>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="blue darken-1" flat @click="onDialogConfirm">确定</v-btn>
          <v-btn color="grey darken-1" flat @click="dialog = false">取消</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <v-dialog v-model="modal" persistent max-width="290">
      <v-card>
        <v-card-title class="title">{{ modalTitle }}</v-card-title>
        <v-card-text class="title">{{ modalContent }}</v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="blue darken-1" flat @click="onModalConfirm">确定</v-btn>
          <v-btn color="grey darken-1" flat @click="modal = false">取消</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>


<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { Task, Order } from "@/api";
import { forEach } from "lodash";
import { KV, Pagination } from "@/utils/type";
import {
  PageOptions,
  TaskStatusKV,
  SiteKV,
  OrderStatusKV
} from "@/utils/constants";
import { ReqTaskOrder, RespFileVo } from "@/api/bean";
import { getTime } from "@/utils/commonUtils";
import Cookie from "js-cookie";

declare const $Vue: Vue;

@Component
export default class OrderList extends Vue {
  private pageOptions: any = [];

  private orderStatus: any = [];
  private sites: Array<KV> = SiteKV;

  private queryForm: any = {
    orderNumber: "",
    siteId: "",
    orderStatus: '',
  };

  private headers: Array<any> = [];

  private tableData: any = [
    // {
    //   orderNumber: "2JGnwe78t4hD34yuHKf43",
    //   siteId: 1,
    //   productAsin: "329907877348",
    //   price: 24,
    //   taskType: 1,
    //   orderStatus: 2,
    //   createTime: "2019-09-01 19:32:41"
    // }
  ];

  private getTime(date: string) {
    return getTime(date);
  }

  private selected = [];

  private imagePreview: string = "";

  private dialog: boolean = false;
  private dialogTitle: string = "";
  private dialogType: number = 1;
  private dialogItem: any = {
    orderImgArr: [],
  };
  private dialogData: any = {};

  private modal: boolean = false;
  private modalTitle: string = "注意!";
  private modalContent: string = "确认取消订单吗?";
  private modalType: number = 1;
  private modalItem: any = {};
  private isQuery: boolean = false;

  private file: any = null;
  private pagination: Pagination = {
    pageCount: 20,
    page: 1,
    limit: 10,
    offset: 0
  };

  private get getTotal() {
    return 0;
  }

  protected mounted() {
    this.getOrderList();

    $Vue.$emit("title", { message: this.$t("base.orderList").toString() });
    this.pageOptions = PageOptions.slice();
    this.orderStatus = OrderStatusKV.slice();
    this.headers = [
      {
        text: this.$t("order.orderId").toString(),
        align: "center",
        sortable: false,
        value: "name"
      },
      {
        text: this.$t("task.site").toString(),
        align: "center",
        sortable: false,
        value: "site"
      },
      { text: "ASIN", align: "center", sortable: false, value: "asin" },
      {
        text: this.$t("order.itemPrice").toString() + "($)",
        align: "center",
        sortable: false,
        value: "price"
      },
      {
        text: this.$t("order.totalPrice").toString() + "(￥)",
        align: "center",
        sortable: false,
        value: "totalPrice"
      },
      {
        text: this.$t("order.taskType"),
        align: "center",
        sortable: false,
        value: "iron"
      },
      {
        text: this.$t("base.status"),
        align: "center",
        sortable: false,
        value: "status"
      },
      {
        text: this.$t("base.createTime"),
        align: "center",
        sortable: false,
        value: "createTime"
      },

      {
        text: this.$t("base.action"),
        align: "center",
        sortable: false,
        value: "action"
      }
    ];
  }

  private onBatchConfirmOrder() {
    if (this.batchValidate()) {
      // this.confirmOrder();
    }
  }

  private onBatchConfirmReview() {
    if (this.batchValidate()) {
      // this.saveReview();
    }
  }

  // 显示确认订单按钮
  private showConfirmOrder(item: any): boolean {
    return item.orderStatus === 5;
  }

  // 显示确认评价按钮
  private showReviewOrder(item: any): boolean {
    return item.orderStatus === 6;
  }

  private batchValidate(): boolean {
    let selected = this.selected;
    if (selected.length === 0) {
      $Vue.$emit("snackbar", {
        message: "请选择订单..."
      });
      return false;
    }
    return true;
  }

  private changeSort() {}

  private toggleAll() {
    if (this.selected.length) {
      this.selected = [];
    } else {
      this.selected = this.tableData.slice();
    }
  }

  private handleOrderList(list: Array<any>) {
    list.forEach((item: any) => {
      let orderImg = null;
      if (item.orderImg) {
        if (item.orderImg.match(/\[/g)) {
          try {
            orderImg = JSON.parse(item.orderImg);
            item.orderImgArr = orderImg;
          } catch (err) {
            console.error(err);
          }
        } else {
          item.orderImgArr = [item.orderImg];
        }
      } else {
        item.orderImgArr = [];
      }
    });
    // console.log(list);
    
    this.tableData = list;
  }

  private onQuery(from?: string) {
    let params: any = {};
    let valid = 0;
    console.error(this.queryForm);
    
    forEach(this.queryForm, (item, key) => {
      // item ? (
        params[key] = item
        // ) : valid++;
    });
    if (valid === 3) {
      // return $Vue.$emit("snackbar", {
      //   message: "请至少填写一个查询条件"
      // });
    }

    if (from === undefined) {
      this.pagination.offset = 0;
      this.pagination.page = 1;
    }
    params.limit = this.pagination.limit;
    params.offset = this.pagination.offset;
    this.isQuery = true;
    this.queryOrder(params);
  }

  private onPageChange(page: any) {
    this.pagination.offset = (page - 1) * this.pagination.limit;
    if (!this.isQuery) {
      this.getOrderList();
    } else {
      this.onQuery("wyvonj");
    }
  }

  // 分页选项改变
  private onPageOptionChange(value: any) {
    this.pagination.page = 1;
    this.pagination.offset = 0;
  }

  private onModalConfirm() {
    if (this.modalType === 1) {
      this.invalidOrder();
    } else if (this.modalType === 2) {
      this.payOrder();
    }
  }

  /**
   * 查看订单详情
   */
  private onDetail(item: any) {
    // this.dialogItem = item;
    // this.dialogData = item;
    // this.dialogType = 3;
    // this.dialog = true;
    // this.dialogTitle = "订单详情";
    sessionStorage.setItem('OrderDetail', JSON.stringify(item));
    this.$router.push({
      name: '订单详情',
    });
    
    // this.getOrderDetail();
  }
  /**
   * 废弃订单
   */
  private onObsolete(item: any) {
    this.modalType = 1;
    this.modal = true;
    this.modalItem = item;
    this.modalContent = "确定废弃该订单吗?";
  }

  /**
   * 支付订单
   */
  private onPay(item: any) {
    this.modalType = 2;
    this.modal = true;
    this.modalItem = item;
    this.modalContent = "是否确认支付订单?";
  }

  /**
   * 确认订单
   */
  private onConfirmOrder(item: any) {
    this.dialogType = 1;
    this.dialog = true;
    this.dialogItem = item;
    this.dialogData = item;
    this.dialogTitle = "确认订单";

    // this.dialogItem.image = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1561033154444&di=7e30761f8da3df03ff5e4bc43e9a7619&imgtype=0&src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20180123%2Fd2a13160d0ef4004a2854dfc673ac9d7.jpeg'
  }

  private onAccomplishOrder(item: any) {
    this.dialogType = 2;
    this.dialog = true;
    this.dialogItem = item;
    this.dialogData = item;
    this.dialogTitle = "确认评价";

    // this.dialogItem = item;
    // this.dialogItem.image = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1561033154444&di=7e30761f8da3df03ff5e4bc43e9a7619&imgtype=0&src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20180123%2Fd2a13160d0ef4004a2854dfc673ac9d7.jpeg'
  }

  private onDialogConfirm() {
    if (this.dialogType === 1) {
      this.confirmOrder();
    } else if (this.dialogType === 2) {
      this.accomplishOrder();
    }
  }

  /**
   * 获取任务列表
   */
  private async getOrderList(queryForm?: any) {
    let params: ReqTaskOrder = {
      offset: this.pagination.offset,
      limit: this.pagination.limit,
      sellerUserId: Number(Cookie.get("seller_userId")),
    };
    if (queryForm) {
      params = queryForm;
      params.sellerUserId = Number(Cookie.get("seller_userId"))
    }

    const { data } = await Order.getOrderList.r(params);
    console.log("getOrderList", data);
    // $Vue.$emit("balance");

    if (data.result === 0) {
      let $data = data.data;
      // this.tableData = $data.dataList;
      this.handleOrderList($data.dataList);

      this.pagination.pageCount = $data.totalCount
        ? Math.ceil($data.totalCount / this.pagination.limit)
        : 1;
    } else {
      $Vue.$emit("snackbar", {
        message: data.message
      });
    }
  }

  /**
   * 查询订单
   */
  private async queryOrder(queryForm: any) {
    const params: ReqTaskOrder = {
      offset: this.pagination.offset,
      limit: this.pagination.limit,
      ...queryForm
    };

    const { data } = await Order.getOrderList.r(params);
    console.log("getTaskList", data);
    if (data.result === 0) {
      let $data = data.data;
      this.tableData = $data.dataList;
      this.pagination.pageCount = $data.totalCount
        ? Math.ceil($data.totalCount / this.pagination.limit)
        : 1;
    } else {
      $Vue.$emit("snackbar", {
        message: data.message
      });
    }
  }

  /**
   * 废弃订单
   */
  private async invalidOrder() {
    const params: any = {
      orderId: this.modalItem.orderId
    };
    const { data } = await Order.invalidOrder.r(params);
    console.log("invalidOrder", data);
    $Vue.$emit("snackbar", {
      message: data.message
    });
    this.modal = false;
    this.getOrderList();
    $Vue.$emit("balance");
  }

  /**
   * 支付订单
   */
  private async payOrder() {
    const params: any = {
      orderId: this.modalItem.orderId
    };
    const { data } = await Order.payOrder.r(params);
    console.log("payOrder", data);
    $Vue.$emit("snackbar", {
      message: data.message
    });
  }

  /**
   * 支付订单
   */
  private async getOrderDetail() {
    const params: any = {
      orderId: this.dialogItem.orderId
    };
    const { data } = await Order.getOrderDetail.r(params);
    console.log("getOrderDetail", data);
    if (data.result === 0) {
      this.dialogData = data.data;
    } else {
      $Vue.$emit("snackbar", {
        message: data.message
      });
    }
  }

  /**
   * 确认订单
   */
  private async confirmOrder() {
    const params: any = {
      orderId: this.dialogItem.orderId
    };
    const { data } = await Order.confirmOrder.r(params);
    console.log("confirmOrder", data);
    this.getOrderList();
    $Vue.$emit("snackbar", {
      message: data.message
    });
    // $Vue.$emit("balance");

    this.dialog = false;
  }

  /**
   * 完成订单
   */
  private async accomplishOrder() {
    const params: any = {
      orderId: this.dialogItem.orderId
    };
    const { data } = await Order.accomplishOrder.r(params);
    console.log("accomplishOrder", data);
    this.dialog = false;
    this.getOrderList();
    // $Vue.$emit("balance");

    $Vue.$emit("snackbar", {
      message: data.message
    });
  }
}
</script>

<style lang="less" scoped>
.tracetask-container {
  width: 100%;
  height: 100%;
}
.pagination-wrapper {
  background: white;
  border-top: 1px solid #d4d4d4;
}

.order-image {
  height: 5rem;
}

.dialog-image {
  width: 80%;
}
</style>


